package top.xiaoshuaila.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import top.xiaoshuaila.config.JwtTokenUtil;
import top.xiaoshuaila.pojo.Admin;
import top.xiaoshuaila.mapper.AdminMapper;
import top.xiaoshuaila.pojo.RespBean;
import top.xiaoshuaila.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 小帅啦
 * @since 2021-05-02
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private AdminMapper adminMapper;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Override
    public RespBean login(String username, String password, HttpServletRequest request) {
        UserDetails userDetails =
                userDetailsService.loadUserByUsername(username);
        if(null==userDetails||!passwordEncoder.matches(password,
                userDetails.getPassword()))
        {
            return RespBean.error("用户名或者密码不正确");
        }
        if(!userDetails.isEnabled())
        {
            return RespBean.error("账号被禁用,请联系管理员");
        }
        System.out.println("success");
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(userDetails
                        ,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String token=jwtTokenUtil.generateToken(userDetails);
        Map<String,String> map=new HashMap<>();
        map.put("token",token);
        map.put("tokenHead",tokenHead);
        return RespBean.success("登录成功",map);
    }

    @Override
    public Admin getAdminByUserName(String username) {
        QueryWrapper<Admin> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.eq("enabled",true);
        return adminMapper.selectOne(queryWrapper);
    }
}
